/*
 * Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
 */

package org.jetbrains.amper.core

import java.time.Instant
import java.util.*

object AmperBuild {
    val isSNAPSHOT: Boolean
    val BuildNumber: String
    private val commitHash: String?
    private val commitShortHash: String?
    private val buildDate: Instant?

    val banner: String
        get() {
            val commitHash = commitShortHash?.let { "+$it" } ?: ""
            return "JetBrains Amper version $BuildNumber$commitHash"
        }

    init {
        this::class.java.getResourceAsStream("/build.properties").use { res ->
            if (res == null) {
                // TODO this is temporary workaround to run Amper built by pure Amper
                // please remove this hack when build.properties will be generated by pure Amper backend too

                isSNAPSHOT = true
                BuildNumber = "1.0-SNAPSHOT"
                commitHash = null
                commitShortHash = null
                buildDate = null

                return@use
            }

            val props = Properties()
            props.load(res)

            fun getProperty(property: String): String {
                val value: String? = props.getProperty(property)
                if (value.isNullOrBlank()) {
                    throw IllegalStateException("Property '$property' is not present in build.properties")
                }
                return value
            }

            BuildNumber = getProperty("version")
            isSNAPSHOT = BuildNumber.contains("-SNAPSHOT")
            commitHash = props.getProperty("commitHash")
            commitShortHash = props.getProperty("commitShortHash")
            buildDate = props.getProperty("commitDate")?.let { Instant.parse(it) }
        }
    }
}
